import clipImage from '../canvas/clipRect'
import { dragable } from '../utils/dom'
/**
 * 添加裁剪事件
 * @param {string} containerId 主容器id, 降附图放到该容器
 * @param {string} overmapId 覆盖mapbox的canvas id && canvas的尺寸和map一致
 * @param {funtion} callback 回调 接受裁剪的dataURL
 */
const defaultOpts = {
  overmapId: 'over-map-canvas',
  containerId: 'draw-container',
  mapTop: 0,
  mapLeft: 0
}
function clipMap(map, options = defaultOpts, callback) {
  const { overmapId, containerId, mapTop, mapLeft } = options
  // 主容器
  const mainContainer = document.getElementById(containerId)
  // 覆盖map的canvas
  const canvas_over_map = document.getElementById(overmapId)
  const { clientWidth, clientHeight } = canvas_over_map
  const ctx = canvas_over_map.getContext('2d')
  ctx.clearRect(0, 0, clientWidth, clientHeight)

  let isdown = false
  let start = [0, 0]
  let width_clip
  let height_clip
  let dom_index = 1
  canvas_over_map.addEventListener('mousedown', e => {
    console.log('mousedown', e)
    const coordinate = map.unproject(new mapboxgl.Point(e.offsetX, e.offsetY))

    isdown = true
    start = [e.offsetX, e.offsetY]
  })
  canvas_over_map.addEventListener('mousemove', e => {
    if (isdown) {
      ctx.clearRect(0, 0, clientWidth, clientHeight)

      ctx.fillStyle = 'rgba(159, 237, 232, .5)'
      ctx.fillRect(
        start[0],
        start[1],
        e.offsetX - start[0],
        e.offsetY - start[1]
      )
    }
  })
  canvas_over_map.addEventListener('mouseup', e => {
    isdown = false
    ctx.clearRect(0, 0, clientWidth, clientHeight)

    // 附图容器
    const div = document.createElement('div')
    div.className = 'attached-map'
    div.style.top = start[1] + mapTop + 'px'
    div.style.left = start[0] + mapLeft + 'px'
    const w = e.offsetX - start[0]
    const h = e.offsetY - start[1]
    div.style.height = h + 'px'
    div.style.width = w + 'px'
    div.innerHTML = `<span class="attached-map-index">${dom_index}</span>` // 图序

    if (w === 0 || h === 0) return
    dom_index++

    // 隐藏canvas
    canvas_over_map.style.display = 'none'

    // ①截取图
    const sourceCanvas = map.getCanvas()
    clipImage(sourceCanvas, start[0], start[1], w, h).then(dataUrl => {
      div.style.backgroundImage = `url(${dataUrl})`
      mainContainer.appendChild(div)
      dragable(div, mainContainer)
    })

    // ②绘制bounds
    const p1 = map.unproject([start[0], start[1]])
    const p2 = map.unproject([start[0], e.offsetX])

    console.log(p1, p2)
  })
}

export { clipMap }
